# -*- coding: utf-8 -*-
"""
****************************
@Time    : 2021/4/30 11:03
@Author  : Candy
@File    : JSON_ENCODE.py
****************************
"""
import json
from datetime import date
from flask.json import JSONEncoder as _JSONEncoder


class MiniJSONEncoder(_JSONEncoder):
    def default(self, o):
        if hasattr(o, 'keys') and hasattr(o, '__getitem__'):
            return dict(o)
        if isinstance(o, date):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        return json.JSONEncoder.default(self, o)


def response_check(**kwargs):
    """
    返回数据校验
    :param kwargs:
    :return:
    """
    code = kwargs.get('code', 200)
    message_en = kwargs.get('message_en', 'success')
    message_zh = kwargs.get('message_zh', '成功')
    data = kwargs.get('data', {})
    return {
        "code": code,
        "message_en": message_en,
        "message_zh": message_zh,
        "data": data
    }


def mini_filter(obj, fields=None, method='DELETE'):
    old_items = [json.loads(json.dumps(i, cls=MiniJSONEncoder)) for i in obj]
    new_items = []
    if fields:
        for item in old_items:
            new_item = {}
            if method == 'DELETE':
                for k in item.copy().keys():
                    if k in fields:
                        item.pop(k)
                new_items.append(item)
            if method == 'NEED':
                for k in item.keys():
                    if k in fields:
                        new_item[k] = item[k]
                new_items.append(new_item)
        return new_items
    else:
        return old_items
